package com.t2c.tibetantochinese.search;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.t2c.tibetantochinese.R;
import com.t2c.tibetantochinese.base.BaseFragment;
import com.t2c.tibetantochinese.common.HttpRequest;
import com.t2c.tibetantochinese.common.HttpRequestManager;
import com.t2c.tibetantochinese.home.HomeFragment;
import com.t2c.tibetantochinese.moudle.SearchNetBean;
import com.t2c.tibetantochinese.utils.CommonUtil;
import com.t2c.tibetantochinese.views.TitleBar;
import com.t2c.tibetantochinese.views.XListView;

/**
 * Created by zoulu on 16/6/20.
 * 搜索翻译
 */
public class SearchFragment extends BaseFragment implements XListView.IXListViewListener{
    private XListView xListView;
    private int page = 1;

    private RelativeLayout re_head;//搜索框
    private RelativeLayout re_search;//搜索框样式
    private EditText edittext;//搜索输入框
    private TextView tv_search;//搜索提示语
    private SearchNetAdapter searchNetAdapter;
    private SearchNetBean dataBean = new SearchNetBean();

    private int type = 1;//1 获取 2搜索

    @Override
    protected int getContentViewResId() {
        return R.layout.search_fragment;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init(view);
        initData();
    }

    private void initData() {
        HttpRequest httpRequest = HttpRequestManager.getInstance().translateGet(new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                SearchNetBean searchNetBean = new Gson().fromJson(response,SearchNetBean.class);
                if(searchNetBean.isSuccess()){
                    page ++;
                    if( searchNetBean.getData().size() > 10){
                        xListView.setPullLoadEnable(true);
                    }else{
                        xListView.setPullLoadEnable(false);
                    }
                    dataBean.getData().addAll(searchNetBean.getData());
                    searchNetAdapter.notifyDataSetChanged();
                }else{
                    Toast.makeText(getActivity(),"Server Error",Toast.LENGTH_SHORT).show();
                    xListView.stopLoadMore();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getActivity(),"Server Error",Toast.LENGTH_SHORT).show();
                xListView.stopLoadMore();
            }
        }, page);
        httpRequest.commit();
    }

    private void init(View view){
        re_head = (RelativeLayout) view.findViewById(R.id.re_head);
        tv_search = (TextView) view.findViewById(R.id.tv_search);
        TextView cancel = (TextView) view.findViewById(R.id.cancel);
        re_search = (RelativeLayout) view.findViewById(R.id.re_search);
        edittext = (EditText) view.findViewById(R.id.edittext);
        ImageView iv_cancel = (ImageView) view.findViewById(R.id.iv_cancel);

        final HomeFragment homeFragment = CommonUtil.getHomeFragment(getActivity());
        TitleBar titleBar = (TitleBar) view.findViewById(R.id.titlebar);
        xListView = (XListView) view.findViewById(R.id.listview);

        xListView.setXListViewListener(this);
        xListView.setPullRefreshEnable(false);
        searchNetAdapter = new SearchNetAdapter(getActivity(),dataBean);
        xListView.setAdapter(searchNetAdapter);

        if(CommonUtil.isChinese(getActivity())) {
            titleBar.setTitle(getResources().getString(R.string.searchtranslate));
            tv_search.setText(getResources().getString(R.string.search));
        }else{
            titleBar.getTitle().setTypeface(CommonUtil.getTibetanType(getActivity()));
            tv_search.setTypeface(CommonUtil.getTibetanType(getActivity()));
            titleBar.setTitle(getResources().getString(R.string.tsearchtranslate));
            tv_search.setText(getResources().getString(R.string.tsearch));
        }
        titleBar.setOnLeftListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                homeFragment.fragmentBack();
            }
        });

        view.findViewById(R.id.re_search).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                type = 2;
                re_search.setVisibility(View.GONE);
                re_head.setVisibility(View.VISIBLE);
                edittext.requestFocus();
                CommonUtil.showKeyBoard(getActivity());
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                re_head.setVisibility(View.GONE);
                re_search.setVisibility(View.VISIBLE);
                CommonUtil.hideKeyboard(getActivity());
                edittext.setText("");
                type = 1;
                //重新加载数据
                page = 1;
                dataBean.getData().clear();
                initData();
            }
        });

        iv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edittext.setText("");
            }
        });

        edittext.setOnEditorActionListener(new TextView.OnEditorActionListener(){
            @Override
            public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
                if(arg1 == EditorInfo.IME_ACTION_SEARCH)
                {
                    if(TextUtils.isEmpty(edittext.getText().toString())){
                        Toast.makeText(getActivity(),"请输入要搜索的内容",Toast.LENGTH_SHORT).show();
                    }else{
                        page = 1;
                        dataBean.getData().clear();
                        getSearchResult(edittext.getText().toString());
                        CommonUtil.hideKeyboard(getActivity());
                    }
                }
                return false;
            }

        });
    }

    private void getSearchResult(String content){
        HttpRequest httpRequest = HttpRequestManager.getInstance().translateAndDicSearch(new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                SearchNetBean searchNetBean = new Gson().fromJson(response,SearchNetBean.class);
                if(searchNetBean.isSuccess()){
                    page ++;
                    if( searchNetBean.getData().size() >= 20){
                        xListView.setPullLoadEnable(true);
                    }else{
                        xListView.setPullLoadEnable(false);
                    }
                    dataBean.getData().addAll(searchNetBean.getData());
                    searchNetAdapter.notifyDataSetChanged();
                }else{
                    Toast.makeText(getActivity(),"Server Error",Toast.LENGTH_SHORT).show();
                    xListView.stopLoadMore();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getActivity(),"Server Error",Toast.LENGTH_SHORT).show();
                xListView.stopLoadMore();
            }
        }, content,page,20);
        httpRequest.commit();
    }

    @Override
    public void onRefresh() {

    }

    @Override
    public void onLoadMore() {
        if(type == 1){
            initData();
        }else if (type == 2){
            getSearchResult(edittext.getText().toString());
        }
    }
}
